package model;

import java.net.InetAddress;
import java.util.concurrent.LinkedBlockingQueue;

import javax.swing.DefaultListModel;

import controller.*;

/**
 * This is the model and all its informations
 */
public class Model {
	
	/**
	 * link to the controller
	 * link to the queue of messages received
	 * link to the queue of messages to send
	 * link to the list of connected users
	 */
	private ChatController chatController;
	private LocalUser user;
	private MsgRcvd bufferRcv;
	private Msg2Snd bufferSnd;
	private UserList userList;
	
	/**
	 * @param chatController is a link to the controller
	 * @param username is the local user's username
	 * @param listMsg2Snd is the queue of messages to send
	 * @param userList is the list of connected users
	 * @param listMsgRcvd is the queue of messages received
	 */
	public Model(ChatController chatController, String username, LinkedBlockingQueue <Msg> listMsg2Snd, DefaultListModel userList, LinkedBlockingQueue <Msg> listMsgRcvd){
		this.chatController = chatController;
		this.user = new LocalUser(username);
		this.bufferRcv = new MsgRcvd(listMsgRcvd);
		this.bufferSnd = new Msg2Snd(listMsg2Snd);
		this.userList = new UserList(userList);
	}
	
	/**
	 * @param username is the local user's username
	 */
	public void setUsername(String username){
		user.setUsername(username);
	}
	
	/**
	 * @return the local user
	 */
	public LocalUser getUser(){
		return user;
	}
	
	/**
	 * adds a remote user to the model
	 * @param nickname is the remote user's nickname
	 * @param ip is the remote user's ip address
	 */
	public void addUser(String nickname, InetAddress ip){
		RemoteUser u = new RemoteUser(nickname, ip);
		this.userList.addUser(u);
	}
	
	/**
	 * removes a user from the model
	 * first, it finds the user in the list with its ip address, then removes it
	 * @param ip is the ip address of the user to delete of the list of connected users
	 */
	public void delUser(InetAddress ip){
		for (int i=0; i<userList.getUserList().getSize(); i++){
			if ( ((RemoteUser)userList.getUserList().get(i)).getIP().equals(ip) ) {
				userList.delUser(((RemoteUser)userList.getUserList().get(i)));
				break;
			}
		}		
	}
	
	/**
	 * adds a message to send to the model
	 * @param m is the message to add to the queue of messages to send
	 */
	public void addMsg2Snd(Msg m){
		this.bufferSnd.getList().add(m);
	}
	
	/**
	 * adds a message received to the model
	 * @param m is the message to add to the queue of received messages
	 */
	public void addMsgRcvd(Msg m){
		this.bufferRcv.getList().add(m);
	}
}
